package titt.service.content;

import titt.util.event.EventAction;
import titt.util.event.TITTEventQueue;
import titt.util.io.pipe.PipeListener;

public class AsyncListener implements PipeListener {
	
	private final PipeListener listener;
	private final TITTEventQueue queue = new TITTEventQueue();
	private final int minInterval;
	private long last;
	
	public AsyncListener(int minInterval, PipeListener listener) {
		this.listener = listener;
		this.minInterval = minInterval;
	}

	public AsyncListener(PipeListener listener) {
		this.listener = listener;
		this.minInterval = -1;
	}
	
	@Override
	public void onComplete(final int total) {
		queue.add(new EventAction() {
			
			@Override
			public void eventPerformed() throws Exception {
				listener.onComplete(total);
				queue.stop();
			}
		});
	}

	@Override
	public void onConnectionUpdate(final int read, final int total) {
		long now = System.currentTimeMillis();
		if(minInterval < 0 || now - last < minInterval)
			return;
		
		last = now;
		

		queue.add(new EventAction() {
			
			@Override
			public void eventPerformed() throws Exception {
				listener.onConnectionUpdate(read, total);
			}
		});	
	}

	@Override
	public void onError() {
		queue.add(new EventAction() {
			
			@Override
			public void eventPerformed() throws Exception {
				listener.onError();
				queue.stop();
			}
		});
	}

	@Override
	public void onInitiate(final int total) {
		queue.add(new EventAction() {
			
			@Override
			public void eventPerformed() throws Exception {
				listener.onInitiate(total);
			}
		});	
	}

}
